<?php

/**
 * Database layer, currently only for MySQL
 *
 * @version $Id$
 * @copyright 2010
 */

class DB
{
	private $conn;
	private $last_query;

	public $last_id = 0;

	/**
	 * Constructor
	 */
	function __construct($dbserver,$dbuser,$dbpassword,$dbname)
	{
		// ------------------------------------------------
		/// CONNECTION TO MYSQL DB AND DATABASE SELECTION
		// ------------------------------------------------

		$this->conn = MySQL_Connect($dbserver, $dbuser , $dbpassword);
		if (!$this->conn):
			die("DB error in connection: ".mysql_error());
		endif;

		$vyberdb = MySQL_Select_DB($dbname, $this->conn);
		if (!$vyberdb):
			die("DB selection error: ".mysql_error());
		endif;
	}

	/**
	 * DB::parse_arguments()
	 * Function for parsing ; in queries
	 * @param mixed $args
	 * @return
	 */
	private function parse_arguments($args)
	{
		global $core;

		if(count($args) == 0)
		{
			$core->err("DB: No arguments for parse_argument function!",1);
		}
		else
		{
			//echo '<br />'.print_r($args);
			$queryString = array_shift($args);
			$tempString = $queryString;
			$queryParts = Array();
			while(mb_strlen($tempString) > 0) {
				$posSemicolon = mb_strpos($tempString, ";");
				$semi = false;
				if($posSemicolon === FALSE)
				{
					$queryParts[] = $tempString;
					break; // break;
				}
				else
				{
					$semi = true;
					$pos = $posSemicolon;
				}

				$toBeParsed = mb_strcut($tempString, 0, $pos);
				$val = array_shift($args);
				if($val === NULL)
				{
					$core->err("DB: No value defined for semicolon replace in query!",1);
				}

				$toBeParsed .= "'" . $this->escape_str($val) . "'";
				$queryParts[] = $toBeParsed;
				$tempString = mb_strcut($tempString, $pos+1);
			}
			$query = implode("", $queryParts);

			return $query;
		}
	}

	/**
	 * DB::escape_str()
	 * Escapes string for DB query. Also checks if magic quotes are enabled and do stripslashes befor escaping
	 * @param mixed $str
	 * @return
	 */
	private function escape_str($str)
	{
		if(get_magic_quotes_gpc() == true)
		{
			$str = stripslashes($str);
		}

		return mysql_real_escape_string($str);
	}

	/**
	 * DB::low_query()
	 * Low level query to DB
	 * @param mixed $query - parsed by parse_arguments function
	 * @return
	 */
	private function low_query($query)
	{
		global $core;

		//echo 'Provadim dotaz: ',$query,'<br />';
		$res = mysql_query($query,$this->conn);
		//1065 - Your query is empty, we dont need this error, it should be handled inside plugins
		if(!$res && mysql_errno() != 1065) $core->err("DB: Error when query: ".mysql_errno().' - '.mysql_error().'<br />Query - '.$query);
		$this->last_query = $res;
		return $res;
	}

	/**
	 * DB::query()
	 * Standard query to DB with replace for ; in query
	 * @param mixed $query
	 * @return
	 */
	public function query($query)
	{
		return $this->low_query($this->parse_arguments(func_get_args()));
	}

	/**
	 * DB::num_rows()
	 * Returns number of rows for given query
	 * @param mixed $query
	 * @return
	 */
	public function num_rows($query = false)
	{
		if($query == false) return mysql_num_rows($this->last_query);
		elseif(is_resource($query)) return mysql_num_rows($query);
		$query = $this->parse_arguments(func_get_args());
		return mysql_num_rows($this->low_query($query));
	}

	/**
	 * DB::get_row()
	 * Returns a single row for given query
	 * @param mixed $query
	 * @return
	 */
	public function get_row($query = false)
	{
		if($query == false) return mysql_fetch_array($this->last_query);
		elseif(is_resource($query)) return mysql_fetch_array($query);
		$query = $this->parse_arguments(func_get_args());
		return mysql_fetch_array($this->low_query($query));
	}

	/**
	 * DB::get_rows()
	 * Returns all rows as array
	 * @param mixed $query
	 * @return
	 */
	public function get_rows($query = false)
	{
		if($query == false) $res = $this->last_query;
		elseif(is_resource($query)) $res = $query;
		else
		{
			$query = $this->parse_arguments(func_get_args());
			$res = $this->low_query($query);
		}

		$result = Array();
		while($row = mysql_fetch_array($res))
		{
			$result[] = $row;
		}
		return $result;
	}

	/**
	 * DB::get_object()
	 * Returns one row for given query as object
	 * @param mixed $query
	 * @return
	 */
	public function get_object($query = false)
	{
		if($query == false) return mysql_fetch_object($this->last_query);
		elseif(is_resource($query)) return mysql_fetch_object($query);
		$query = $this->parse_arguments(func_get_args());
		return mysql_fetch_object($this->low_query($query));
	}

	/**
	 * DB::get_objects()
	 * Returns all rows for given query as array of objects
	 * @param mixed $query
	 * @return
	 */
	public function get_objects($query = false)
	{
		if($query == false) $res = $this->last_query;
		elseif(is_resource($query)) $res = $query;
		else
		{
			$query = $this->parse_arguments(func_get_args());
			$res = $this->low_query($query);
		}

		$result = Array();
		while($row = mysql_fetch_object($res))
		{
			$result[] = $row;
		}
		return $result;
	}

	/**
	 * DB::get_last_id()
	 * Return ID of last INSERT query
	 * @return
	 */
	public function get_last_id()
	{
		return mysql_insert_id();
	}
}
?>